﻿using System;
using System.Configuration;
using Microsoft.WindowsAzure.ServiceRuntime;

namespace WebTestHarness
{
    public static class ConfigUtil
    {
        /// <summary>
        /// Gets a configuration setting from application settings in the Web.config or App.config file. 
        /// When running in a hosted environment, configuration settings are read from .cscfg
        /// files.
        /// </summary>
        public static string GetConfigSetting(string configSetting)
        {
            string ret = null;

            // First, try to read from appsettings
            ret = TryGetAppSetting(configSetting);

            // settings in the csc file overload settings in Web.config
            if (RoleEnvironment.IsAvailable)
            {
                string cscRet = TryGetConfigSetting(configSetting);

                if (!string.IsNullOrEmpty(cscRet))
                {
                    ret = cscRet;
                }
            }

            return ret;
        }

        private static string TryGetConfigSetting(string configName)
        {
            string ret = null;
            try
            {
                ret = RoleEnvironment.GetConfigurationSettingValue(configName);
            }
            catch (Exception)
            {
                return null;
            }
            return ret;
        }

        private static string TryGetAppSetting(string configName)
        {
            string ret = null;
            try
            {
                ret = ConfigurationSettings.AppSettings[configName];
            }
            // some exception happened when accessing the app settings section
            // most likely this is because there is no app setting file
            // we assume that this is because there is no app settings file; this is not an error
            // and explicitly all exceptions are captured here
            catch (Exception)
            {
                return null;
            }
            return ret;
        }
    }
}